package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.service.IUserService;
import jakarta.servlet.http.HttpSession;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class UserController {

    @Autowired
    private IUserService userService;

    //转发到首页页面
    @RequestMapping("/index.html")
    public String index() {
        return "index";
    }

    //转发到登录页面
    @RequestMapping("/login.html")
    public String login() {
        return "login";
    }

    //转发到登录页面
    @RequestMapping("/register.html")
    public String register() {
        return "register";
    }


    @RequestMapping("/login.do")
    public String login(String usrAccount, String usrPassword) {
        try {
            // 获取当前用户 Subject
            Subject subject = SecurityUtils.getSubject();
            // 创建认证令牌
            UsernamePasswordToken token = new UsernamePasswordToken(usrAccount, usrPassword);
            // 执行登录
            subject.login(token);
            return "redirect:/index.html";//重定向
        } catch (Exception e) {
            return "login";
        }
    }

    @RequestMapping("/logout.do")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/index.html";
    }

    @RequestMapping("/register.do")
    public String register(String usrAccount, String usrPassword) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("usr_account", usrAccount);
        User user = new User();
        user.setUsrAccount(usrAccount);
        user.setUsrPassword(usrPassword);
        boolean flag = userService.register(user);
        if (flag) {
            return "redirect:/index.html";
        }
        return "register";
    }

    //转发到登录页面
    @RequestMapping("/xxx.html")
    public String xxx() {
        throw new RuntimeException("除0异常");
    }

}
